<template>
  <div class="search-suggestion">
    <van-cell icon="search" v-for="(obj, index) in suggestions" :key="index" @click="$emit('search',obj)">
      <!-- <div slot="title" v-html="highlightText(obj)"></div> -->
      <template #title>
        <div v-html="highlightText(obj)"></div>
      </template>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestion } from '@/api/search.js'
import { debounce } from 'lodash'
export default {
  name: 'SearchSuggestion',
  props: {
    // 从父组件传过来的输入框的值
    searchtext: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      suggestions: []
    }
  },
  watch: {
    // 监听传过来的值的改变
    searchtext: {
      //   handler(newvalue) {
      //     // 每次变化都会调用一次这个函数
      //     this.loadSearchSuggestion(newvalue);
      //   },
      // 用lodash工具库的debounce函数来做一个防抖搜索
      handler: debounce(function (newvalue) {
        this.loadSearchSuggestion(newvalue)
      }, 1000),
      // 直接先监听一次改变
      immediate: true
    }
  },
  methods: {
    async loadSearchSuggestion (q) {
      try {
        const { data } = await getSearchSuggestion(q)
        this.suggestions = data.data.options
        // console.log(data.data.options);
      } catch (error) {
        this.$toast('获取搜索联想列表失败', error)
      }
    },
    // 高亮关键字替换
    highlightText (text) {
      // 我觉得new RegExp()创建正则匹配与字面量创建正则区别就是前者可以用变量后者不可以
      // 将要被转换成的字符串
      const highlightStr = `<span class="active">${this.searchtext}</span>`
      // 需要替换的字符串
      const reg = new RegExp(this.searchtext, 'gi')
      // 传进来的值replace替换 reg 改成 highlightStr
      //   console.log(text.replace(reg, highlightStr));
      // 返回一个新的字符串
      return text.replace(reg, highlightStr)
    }
  }
}
</script>

<style scoped lang="less">
/deep/ .van-cell__title {
  .active {
    color: #3296fa !important;
  }
}
</style>
